import { createRouter, createWebHistory } from 'vue-router'
import LoginView from '../views/LoginView.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: () => import('../views/HomeView.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/login',
      name: 'login',
      component: LoginView,
      meta: { guest: true }
    },
    {
      path: '/register',
      name: 'register',
      component: () => import('../views/RegisterView.vue'),
      meta: { guest: true }
    }
  ]
})

// 记录重定向状态，避免循环
let isRedirecting = false;

// 导航守卫 - 检查是否已登录
router.beforeEach((to, from, next) => {
  // 如果正在重定向中，直接放行，防止循环
  if (isRedirecting) {
    isRedirecting = false;
    return next();
  }
  
  const accessToken = localStorage.getItem('access_token')
  
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // 需要登录的路由
    if (!accessToken) {
      isRedirecting = true;
      next({ name: 'login' })
    } else {
      next()
    }
  } else if (to.matched.some(record => record.meta.guest)) {
    // 访客路由（登录/注册）
    if (accessToken) {
      // 已登录用户访问登录/注册页，重定向到首页
      isRedirecting = true;
      next({ name: 'home' })
    } else {
      next()
    }
  } else {
    // 其他不需要特殊处理的路由
    next()
  }
})

export default router 